/**
* ...
* @author Ankur Arora
* @version 1.0
*/

import mx.video.FLVPlayback;


class classes.utils.SWFDownloader
{


	private var m_arrSwfList:Array;
	private var m_objLoader:MovieClipLoader;
	private var m_intCurrentDonwloadIndex:Number;
	private static var m_mcOwner:MovieClip;
	private static var m_mcPreloader:MovieClip;

	public function SWFDownloader(mcOwner:MovieClip)
	{
		m_arrSwfList = new Array();
		m_intCurrentDonwloadIndex = 0;
		m_objLoader = new MovieClipLoader();
		m_mcOwner = mcOwner;
		createSwfEvents();
	}

	public function startDownloadingList():Void
	{
		if(m_intCurrentDonwloadIndex < m_arrSwfList.length)
		{
			m_mcPreloader.removeMovieClip();
			m_mcPreloader = m_mcOwner.createEmptyMovieClip("m_mcPreloader", m_mcOwner.getNextHighestDepth());
			m_objLoader.loadClip(m_arrSwfList[m_intCurrentDonwloadIndex].swfFile, m_mcPreloader);
		}
		trace("m_mcPreloader " + m_arrSwfList[m_intCurrentDonwloadIndex].swfFile)
	}

	public function addSwfToQueue(strSwfPath:String):String
	{
		m_arrSwfList.push({swfFile: strSwfPath, isDownloaded:false});
		return "Video added to the Queue for downloading";
	}

	private function createSwfEvents():Void
	{
		var objThis = this;
		var eventObject:Object = new Object();
		eventObject.onLoadComplete = function(mcSource:MovieClip, httpStatus:Number):Void
		{
			objThis.m_intCurrentDonwloadIndex++;
			objThis.startDownloadingList();
		}

		eventObject.onLoadInit = function(mcSource:MovieClip)
		{
			m_mcPreloader._visible = false;
			mcSource.stop();
		}

		eventObject.onLoadError = function(mcSource:MovieClip, errorCode:String, httpStatus:Number) {
			objThis.m_intCurrentDonwloadIndex++;
			objThis.startDownloadingList();
		}

		m_objLoader.addListener(eventObject);
	}

	private function searchForItemIndex(strSearchString:String):Number
	{
		for (var i:Number=0; i<m_arrSwfList.length; i++)
		{
			if(strSearchString == m_arrSwfList[i].videoFile && m_arrSwfList[i].isDownloaded == false)
			{
				return i;
			}
		}
		return -1;
	}



	/*
	public function removeVideoFromQueue(strVideoPath:String):String
	{
		var intItemIndex = searchForItemIndex(strVideoPath);

		if(intItemIndex == -1)
		{
			return "Video is not avialable in list or already downloaded";
		}
		else
		{
			m_arrSwfList.splice(intItemIndex,1);
			return "Video removed from the Queue fow downloading";
		}
	}
	*/


}